var code_err_msg = "";

var getTariffClassVal = function(){
  var tariff_class_ids = $("#tariff_class_select").val();
  $("#tariff_class_ids").val(tariff_class_ids);
}

var getCityVal = function(){
    var city_ids = $("#city_select").val();
    $("#city_ids").val(city_ids);
}

var alert_detail_msg = function(){
  var ue = UE.getEditor('detail');
  var text = ue.getContent();
  if (text.length < 1) {
    $("#alert_detail_msg").show();
    $("#edui1_iframeholder").removeClass("green_border");
    $("#edui1_iframeholder").addClass("red_border");
    return false;
  }else{
    $("#alert_detail_msg").hide();
    $("#edui1_iframeholder").removeClass("red_border");
    $("#edui1_iframeholder").addClass("green_border");
    return true;
  }
}
function visible(state) {
    if("1" == state){//展示属地框
        $("#localizedCities").css("display","block");
    }else{
        $("#localizedCities").css("display","none");
    }
}
$(function() {
   visible($("#localized").val());

    $("#all").click(function(){
        if(this.checked){
            $("#list :checkbox").prop("checked", true);
        }else{
            $("#list :checkbox").prop("checked", false);
        }
    });

   //selectAll("#city_select");
  $("#_localized").on({
      'switchChange.bootstrapSwitch': function(event, state) {
          var val = state?"1":"0";
          $("#localized").val(val);
          visible(val);
      }
  });


  $("#alert_detail_msg").hide();
    //var ue = UE.getEditor('detail');
  var ue = UE.getEditor('detail', {
    toolbars: [
      [
        'fullscreen', '|', 'undo', 'redo', '|',
        'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript',
        'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
        'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
        'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
        'directionalityltr', 'directionalityrtl', 'indent', '|',
        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
        'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
        'simpleupload', 'insertimage', 'emotion', 'scrawl', 'attachment',
        'pagebreak', 'template', '|',
        'horizontal',  'spechars', 'snapscreen', 'wordimage', '|',
        'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
        'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|'
      ]
    ]
  });
    ue.addListener('blur',function(editor){
    alert_detail_msg();
  });
  getTariffClassVal();
  console.log("base=" + base);
  /*表单验证：begin*/
  var $myField = null;
  var myMsg = "";
  $("#frm").validator({
    // 域通过验证时回调
    onValid: function (validity) {
      $(validity.field).closest('.am-form-group').find('.am-alert').hide();
    },
    // 验证出错时的回调， validity 对象包含相关信息，格式通 H5 表单元素的 validity 属性
    onInValid: function (validity) {
      var $field = $(validity.field);
      var field_id = $field.attr('id');

      var $group = $field.closest('.am-form-group');
      var $alert = $group.find('.am-alert');
      var msg = "";
      if ($myField && myMsg && $field.val() && $field.is($myField)) {
        msg = myMsg;
        $myField = null;
        myMsg = "";
      } else if(field_id=="code"){
        msg = code_err_msg;
      }else {
        // 使用自定义的提示信息 或 插件内置的提示信息
        msg = $field.data('validationMessage') || this.getValidationMessage(validity);
      }
      if (!$alert.length) {
        $alert = $("<div class='am-alert am-alert-danger'></div>").hide().
            appendTo($group.find(".input-msg"));
      }
      console.log("onInValid : " + $field.val());
      $alert.html(msg).show();
    },
    //自定义验证
    validate: function (validity) {

      var comparer = function (v1, v2) {
        var date1 = new Date(Date.parse(v1));
        var date2 = new Date(Date.parse(v2));
        if (date1.getTime() > date2.getTime()) {
          validity.valid = false;
        }
      };
      if ($(validity.field).is('#end_time') || $(validity.field).is('#start_time')) {
        var put_on_time = $('#start_time').val();
        var put_off_time = $('#end_time').val();
        comparer(put_on_time, put_off_time);
      };

      /**
       * 校验地市资费代码的唯一性
       */
      var validityCodeUnique = function(){
        var code = $("#code").val();
        var communicationId = $("#communicationId").val();
        var params = {code:code,communicationId:communicationId};
        if(code && code.trim().length>1){
          $.ajax({
            type: "post",
            url: "../tariff/validityCodeUnique",
            data: params,
            dataType: "json",
            async:false,
            success: function(data) {
              if(data.resultCode != 1000){
                code_err_msg = "业务/短信代码已存在";
                validity.valid = false;
              }else{
                validity.valid = true;
              }
            },
            error : function(textStatus) {
              validity.valid = false;
            }
          });
        }else{
          code_err_msg = "输入业务/短信代码,2-30个字符";
          validity.valid = false;
        }
      };
      if ($(validity.field).is('#code')) {
        validityCodeUnique();
      };

      if ($(validity.field).is('#name')) {
        var name = $("#name").val().trim();
        if(!name || name.length<2){
          validity.valid = false;
        }
      };


    },
    submit: function () {
      var formValidity = this.isFormValid();
      var detail_val = alert_detail_msg();
      if($("input[name='city_ids']:checked").length == 0 && "1" == $("#localized").val()){
          alert("至少选择一个地市");
          return false;
      }
      // 表单验证成功，弹出确认提示
      if (formValidity && detail_val) {
        return true;
      }
      console.warn('验证状态：', (formValidity && detail_val) ? '通过' : '未通过');
      return false;
    }
  });
});



